import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_pin_code_fields/flutter_pin_code_fields.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/constants.dart';

import '../../../theme.dart';
import '../../../widget/tag.dart';
import 'logic.dart';

class OrderPaidCreatePage extends StatelessWidget {
  OrderPaidCreatePage({Key? key}) : super(key: key);

  final logic = Get.find<OrderPaidCreateLogic>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('创建付款订单'),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            size: 16.w,
          ),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Form(
        key: logic.formKey,
        child: ListView(
          children: [
            SizedBox(height: kSpaceMedium),
            // 付款金额
            _buildPaidAmount(),

            SizedBox(height: kSpaceMedium),

            // 付款方式
            _buildPayeeInfo(),

            SizedBox(height: kSpaceMedium),

            // 上传附件
            Obx(() => _buildUploadAttachments()),

            SizedBox(height: kSpaceMedium),

            Obx(() => _buildFinancialVoucher()),

            SizedBox(height: kSpaceMedium),

            // 选择关联案件
            Obx(() => _buildSelectCaseBtn()),

            SizedBox(height: kSpaceMedium),

            // 备注
            _buildRemark(),

            // 提交按钮
            Padding(
                padding: EdgeInsets.symmetric(horizontal: kSpaceSmall),
                child: _buildSubmitButton()),
            SizedBox(height: kSpaceSmall),
          ],
        ),
      ),
    );
  }

  Widget _buildModuleTitle(String title) {
    return Text(
      title,
      style: TextStyle(
        fontSize: kFontSizeMedium,
        color: AppColor.colorFontBlack,
        fontWeight: AppFont.fontMedium,
      ),
    );
  }

  Widget _buildModuleBg(EdgeInsetsGeometry? padding, List<Widget> children) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(kRadiusMedium),
        color: Colors.white,
      ),
      padding: padding,
      margin: EdgeInsets.symmetric(horizontal: kSpaceSmall),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: children,
      ),
    );
  }

  Widget _buildPaidAmount() {
    return _buildModuleBg(
      EdgeInsets.all(kSpaceMedium),
      [
        _buildModuleTitle('付款金额'),
        SizedBox(height: kSpaceTiny),

        // 付款金额
        TextFormField(
          controller: logic.amountController,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
            icon: SvgPicture.asset(
              'assets/icons/ic_money.svg',
              width: 40.w,
              height: 40.w,
            ),
            contentPadding:
                EdgeInsets.only(top: kSpaceSmall, bottom: kSpaceMini),
            border: InputBorder.none,
          ),
          validator: (value) {
            if (value == null || value.isEmpty) {
              return '请输入收款金额';
            }
            // 金额正则验证
            if (!RegExp(r'^[0-9]+(.[0-9]{1,2})?$').hasMatch(value)) {
              return '请输入正确的金额';
            }
            return null;
          },
        ),
        Container(
          width: double.maxFinite,
          height: 0.5,
          color: AppColor.colorLineGrey,
        ),
      ],
    );
  }

  // 填写收款人信息模块
  Widget _buildPayeeInfo() {
    return _buildModuleBg(null, [
      Padding(
        padding: EdgeInsets.symmetric(
          horizontal: kSpaceMedium,
          vertical: kSpaceSmall,
        ),
        child: _buildModuleTitle('收款人信息'),
      ),
      Container(
        width: double.maxFinite,
        height: 0.5,
        color: AppColor.colorLineGrey,
      ),
      Padding(
        padding: EdgeInsets.symmetric(
          horizontal: kSpaceMedium,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '户名',
              style: TextStyle(
                fontSize: kFontSizeMedium,
                fontWeight: AppFont.fontRegular,
                color: AppColor.colorFontBlack,
              ),
            ),
            Expanded(
              child: TextFormField(
                textAlign: TextAlign.right,
                controller: logic.bankAccountNameController,
                decoration: InputDecoration(
                  hintText: '请输入',
                  hintStyle: TextStyle(
                    fontSize: kFontSizeMedium,
                    color: AppColor.colorFontLabelGrey,
                  ),
                  contentPadding:
                      EdgeInsets.only(top: kSpaceSmall, bottom: kSpaceMini),
                  border: InputBorder.none,
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入银行户名';
                  }
                  return null;
                },
              ),
            ),
          ],
        ),
      ),
      Padding(
        padding: EdgeInsets.symmetric(
          horizontal: kSpaceMedium,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '银行账号',
              style: TextStyle(
                fontSize: kFontSizeMedium,
                fontWeight: AppFont.fontRegular,
                color: AppColor.colorFontBlack,
              ),
            ),
            Expanded(
              child: TextFormField(
                textAlign: TextAlign.right,
                controller: logic.bankAccountController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  hintText: '请输入',
                  hintStyle: TextStyle(
                    fontSize: kFontSizeMedium,
                    color: AppColor.colorFontLabelGrey,
                  ),
                  contentPadding:
                      EdgeInsets.only(top: kSpaceSmall, bottom: kSpaceMini),
                  border: InputBorder.none,
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入银行账号';
                  }
                  // 银行账号正则验证
                  if (!RegExp(r'^[0-9]*$').hasMatch(value)) {
                    return '请输入正确的银行账号';
                  }
                  return null;
                },
              ),
            ),
          ],
        ),
      ),
      Padding(
        padding: EdgeInsets.symmetric(
          horizontal: kSpaceMedium,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '开户银行',
              style: TextStyle(
                fontSize: kFontSizeMedium,
                fontWeight: AppFont.fontRegular,
                color: AppColor.colorFontBlack,
              ),
            ),
            Expanded(
              child: TextFormField(
                textAlign: TextAlign.right,
                controller: logic.bankNameController,
                decoration: InputDecoration(
                  hintText: '请输入',
                  hintStyle: TextStyle(
                    fontSize: kFontSizeMedium,
                    color: AppColor.colorFontLabelGrey,
                  ),
                  contentPadding:
                      EdgeInsets.only(top: kSpaceSmall, bottom: kSpaceMini),
                  border: InputBorder.none,
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入开户银行名称';
                  }
                  return null;
                },
              ),
            ),
          ],
        ),
      ),
    ]);
  }

  // 财务凭证模块
  Widget _buildFinancialVoucher() {
    return _buildModuleBg(
      EdgeInsets.only(
          left: kSpaceMedium,
          right: kSpaceMedium,
          top: kSpaceMedium,
          bottom: kSpaceTiny),
      [
        _buildModuleTitle('财务凭证'),
        SizedBox(height: kSpaceMini),
        Text(
          '总计：${logic.invoiceTotalAmount.value}',
          style: TextStyle(
            fontSize: kFontSizeSmall,
            color: AppColor.colorFontBlack,
            fontWeight: AppFont.fontRegular,
          ),
        ),
        SizedBox(height: kSpaceMini),
        Center(
          child: FilledButton(
            onPressed: () => logic.toSelectInvoice(),
            child: const Text('选择发票及公益小时单'),
          ),
        ),
        SizedBox(height: kSpaceMini),
      ],
    );
  }

  // 上传附件模块
  Widget _buildUploadAttachments() {
    return _buildModuleBg(
      EdgeInsets.only(
          left: kSpaceMedium,
          right: kSpaceMedium,
          top: kSpaceMedium,
          bottom: kSpaceTiny),
      [
        _buildModuleTitle('附件'),
        SizedBox(height: kSpaceMini),
        if (logic.attachmentNames.isNotEmpty)
          ...List.generate(
            logic.attachmentNames.length,
            (index) => Container(
              padding: EdgeInsets.only(left: kSpaceMedium),
              margin: EdgeInsets.only(top: kSpaceMini),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(kRadiusMedium),
                color: AppColor.colorTagBlue,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Text(
                      logic.attachmentNames[index],
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: kFontSizeSmall,
                        color: AppColor.colorFontBlue,
                        fontWeight: AppFont.fontRegular,
                      ),
                    ),
                  ),
                  IconButton(
                    onPressed: () => logic.deleteFile(index),
                    icon: const Icon(Icons.close, color: Color(0xFFC7C8DB)),
                  ),
                ],
              ),
            ),
          ),
        FilledButton(
          onPressed: () => {logic.pickFile()},
          style: ElevatedButton.styleFrom(
            foregroundColor: AppColor.colorFontBlue,
            backgroundColor: Colors.transparent,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(kRadiusSmall),
            ),
            padding: EdgeInsets.zero,
          ),
          child: Center(
            child: SvgPicture.asset(
              'assets/buttons/ic_upload.svg',
              width: 111.5.w,
              height: 21.w,
            ),
          ),
        ),
      ],
    );
  }

  // 选择关联案件按钮
  Widget _buildSelectCaseBtn() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: kSpaceSmall),
      child: Ink(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(kRadiusMedium),
          color: Colors.white,
        ),
        child: InkWell(
          borderRadius: BorderRadius.circular(kRadiusMedium),
          onTap: () {
            if (logic.caseList.isEmpty) {
              EasyLoading.showToast('暂无案件数据');
            } else {
              _showBottomSheet();
            }
          },
          child: Padding(
            padding: EdgeInsets.symmetric(
              horizontal: kSpaceSmall,
              vertical: kSpaceSmall,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '关联案件',
                      style: TextStyle(
                        fontSize: kFontSizeMedium,
                        color: AppColor.colorFontBlack,
                        fontWeight: AppFont.fontRegular,
                      ),
                    ),
                    const Icon(
                      Icons.keyboard_arrow_down,
                      color: AppColor.colorFontBlack,
                    ),
                  ],
                ),
                SizedBox(height: kSpaceMini),
                logic.selectedCases.isNotEmpty
                    ? Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: List.generate(
                          logic.selectedCases.length,
                          (index) => Padding(
                            padding: EdgeInsets.only(top: kSpaceMini),
                            child: Tag(
                              text: logic.selectedCases[index]!.name,
                              textColor: AppColor.colorFontBlue,
                              textSize: kFontSizeMini,
                              padding: EdgeInsets.all(14.w),
                              borderColor: AppColor.colorFontBlue,
                              borderRadius: kRadiusMedium,
                              leftIcon: Icon(
                                Icons.done,
                                size: 15.w,
                                color: AppColor.colorFontBlue,
                              ),
                            ),
                          ),
                        ),
                      )
                    : Text(
                        '请选择案件',
                        style: TextStyle(
                          color: AppColor.colorFontGrey,
                          fontSize: kFontSizeSmall,
                          fontWeight: AppFont.fontRegular,
                        ),
                      ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildRemark() {
    return _buildModuleBg(EdgeInsets.all(kSpaceMedium), [
      _buildModuleTitle('备注'),
      TextFormField(
        controller: logic.remarkController,
        decoration: InputDecoration(
          hintText: '请输入备注信息',
          hintStyle: TextStyle(
            fontSize: kFontSizeSmall,
            color: AppColor.colorFontLabelGrey,
          ),
          border: InputBorder.none,
          contentPadding: EdgeInsets.only(top: kSpaceSmall, bottom: kSpaceMini),
        ),
        maxLines: 5,
      ),
    ]);
  }

  // 生成提交按钮小部件
  Widget _buildSubmitButton() {
    return Container(
      height: 50.w,
      margin: EdgeInsets.only(top: kSpaceMedium),
      child: FilledButton(
        onPressed: () => {
          if (logic.formKey.currentState!.validate())
            {
              logic.formKey.currentState!.save(),
              if (!logic.commonService.isAssistant())
                {
                  _showPasswordDialog(),
                }
              else
                {
                  logic.submit(),
                }
            }
        },
        child: const Text('提交'),
      ),
    );
  }

  // 底部关联案件弹窗
  void _showBottomSheet() {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: Get.context!,
      isDismissible: false,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(15.w)),
      ),
      builder: (context) {
        return SizedBox(
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: EdgeInsets.only(
                  left: kSpaceMedium,
                  top: kSpaceTiny,
                  bottom: kSpaceTiny,
                  right: kSpaceTiny,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '请选择关联案件',
                      style: TextStyle(
                        fontSize: kFontSizeMedium,
                        color: AppColor.colorFontBlack,
                      ),
                    ),
                    IconButton(
                      onPressed: () => {
                        logic.onCanceledSelectedCase(),
                        FocusScope.of(Get.context!).unfocus(),
                        Get.back()
                      },
                      icon: SvgPicture.asset(
                        'assets/icons/ic_cancel_black.svg',
                        width: kIconSizeMini,
                      ),
                    ),
                  ],
                ),
              ),
              const Divider(),
              Expanded(
                child: ListView.builder(
                  itemCount: logic.caseList.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text(
                        logic.caseList[index]!.name,
                        style: TextStyle(
                          fontSize: kFontSizeSmall,
                          color: AppColor.colorFontBlack,
                        ),
                      ),
                      subtitle: Text(
                        logic.caseList[index]!.caseDate,
                        style: TextStyle(
                          fontSize: kFontSizeMini,
                          color: AppColor.colorFontGrey,
                        ),
                      ),
                      trailing: Obx(
                        () => logic.selectedCaseIndies.contains(index)
                            ? SvgPicture.asset(
                                'assets/icons/ic_radio_selected.svg',
                                width: 16.w)
                            : SvgPicture.asset(
                                'assets/icons/ic_radio_unselect.svg',
                                width: 16.w),
                      ),
                      onTap: () => logic.onSelectedCase(index),
                    );
                  },
                ),
              ),
              const Divider(),
              Padding(
                padding: EdgeInsets.all(kSpaceMedium),
                child: Row(
                  children: [
                    Expanded(
                      child: FilledButton(
                        onPressed: () => logic.onCreateCase(),
                        child: Container(
                          alignment: Alignment.center,
                          height: 50.w,
                          child: Text(
                            '创建案件',
                            textAlign: TextAlign.center,
                            style: TextStyle(fontSize: kFontSizeMedium),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: kSpaceMedium),
                    Expanded(
                      child: Obx(
                            () => FilledButton(
                          onPressed: logic.selectedCaseIndies.isEmpty
                              ? null
                              : () =>
                          {logic.onConfirmSelectedCase(), Get.back()},
                          child: Container(
                            alignment: Alignment.center,
                            height: 50.w,
                            child: Text(
                              '确认',
                              textAlign: TextAlign.center,
                              style: TextStyle(fontSize: kFontSizeMedium),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  void _showPasswordDialog() {
    logic.initPasswordController();

    showModalBottomSheet(
        context: Get.context!,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(15.w)),
        ),
        builder: (context) {
          return SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: kSpaceTiny),
                  Stack(
                    alignment: Alignment.center,
                    children: [
                      Align(
                        alignment: Alignment.center,
                        child: Text(
                          textAlign: TextAlign.center,
                          '请输入6位支付密码',
                          style: TextStyle(
                            fontSize: kFontSizeMedium,
                            color: AppColor.colorFontBlack,
                          ),
                        ),
                      ),
                      Align(
                        alignment: Alignment.centerRight,
                        child: IconButton(
                          onPressed: () => {Get.back()},
                          icon: SvgPicture.asset(
                              'assets/icons/ic_cancel_black.svg',
                              width: kIconSizeMini),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: kSpaceTiny),
                  const Divider(),
                  SizedBox(height: kSpaceBig),
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: kSpaceLarge),
                    child: PinCodeFields(
                      length: 6,
                      autofocus: true,
                      fieldWidth: 40.w,
                      fieldHeight: 40.w,
                      padding: EdgeInsets.only(top: 4.w),
                      fieldBackgroundColor: AppColor.colorRectangleGrey,
                      fieldBorderStyle: FieldBorderStyle.square,
                      borderColor: AppColor.colorRectangleGrey,
                      activeBorderColor: AppColor.colorRectangleGrey,
                      activeBackgroundColor: AppColor.colorRectangleGrey,
                      borderRadius: BorderRadius.circular(5.w),
                      keyboardType: TextInputType.number,
                      obscureText: true,
                      textStyle: TextStyle(
                        fontSize: kFontSizeBig,
                        color: AppColor.colorFontBlack,
                      ),
                      controller: logic.payPasswordController,
                      onComplete: (text) => {
                        Get.back(),
                        logic.submit(),
                      },
                    ),
                  ),
                  SizedBox(height: kSpaceBig),
                ],
              ),
            ),
          );
        });
  }
}
